package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @author: Mr_Sun
 * @Date: 2018/9/3
 * @Time: 18:26
 */
@Service
public class UpLoadService {
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg","image/gif");
    private static final Logger logger = LoggerFactory.getLogger(UpLoadService.class);
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private ThumbImageConfig thumbImageConfig;//缩略图用到的

    public String upload(MultipartFile file) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String contentType = file.getContentType();
            if (!suffixes.contains(contentType)) {
                //类型不匹配  直接返回空
                return null;
            }
            //1.2校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (null == image) {
                //内容有问题
                return null;
            }
            // 2、将图片上传到FastDFS
            // 2.1、获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 2.2、上传
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), extension, null);
//            // 获取缩略图路径
//            String path = thumbImageConfig.getThumbImagePath(storePath.getPath());
            return "http://image.leyou.com/"+storePath.getFullPath();
        } catch (IOException e) {
            logger.error("文件上传失败:文件名: {}", file.getOriginalFilename(), e);
            return null;
        }
    }
}
